package com.xiaobao.campusLostFoundAfter.controller;

import com.xiaobao.campusLostFoundAfter.common.Result;
import com.xiaobao.campusLostFoundAfter.config.FileStorageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    private final FileStorageUtil fileStorageUtil;

    public UploadController(FileStorageUtil fileStorageUtil) {
        this.fileStorageUtil = fileStorageUtil;
    }

    /**
     * 处理图像上传请求
     *
     * @param file 用户上传的图像文件，通过表单字段 "image" 传递
     * @param userId 用户ID，用于创建存储图像的目录
     * @return 返回一个Result对象，包含上传图像的信息，如URL、大小和类型
     */
    @PostMapping("/image")
    public Result<Map<String, Object>> uploadImage(@RequestParam("image") MultipartFile file,
                                                   @RequestParam String userId) {
        try {
            // 验证文件是否为空
            if (file.isEmpty()) {
                return Result.error("上传的文件为空");
            }

            // 存储文件（使用userId作为学号创建目录）
            String imageUrl = fileStorageUtil.storeFile(file, userId);

            // 构建返回数据
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("url", imageUrl);
            resultData.put("size", formatFileSize(file.getSize()));
            resultData.put("type", file.getContentType());

            return Result.success(resultData);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (IOException e) {
            log.error("上传失败: {}", e.getMessage());
            return Result.error("上传失败，请重试");
        }
    }

    /**
     * 格式化文件大小为可读格式
     */
    private String formatFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return String.format("%.2f %s", size / Math.pow(1024, digitGroups), units[digitGroups]);
    }
}